<?php

namespace app\admin\controller;

use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;




use app\common\controller\Backend;

/**
 * 字体管理
 *
 * @icon fa fa-font
 */
class Font extends Backend
{
    
    /**
     * Font模型对象
     * @var \app\admin\model\Font
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Font;

    }

    public function import()
    {
        parent::import();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {




            $params = $this->request->post("row/a");
            if ($params) {

                // halt($params);
                if(empty($params['b_id'])){
                    $this->error('请选择版');
                }

                if(empty($params['biaoge'])){
                    $this->error('请选上传表格');
                }
                Db::name('b')->where('id',$params['b_id'])->update(['status'=>'2']);
                $this->success('成功添加'.$this->biaoge($params));

                // $T = new \app\api\controller\Tpmecmscom;
                // $fontcate_id = $T->GetFontcateIdByBId($params['b_id']);
                // GetPId
                

                // $params = $this->preExcludeFields($params);

                // if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                //     $params[$this->dataLimitField] = $this->auth->id;
                // }
                // $result = false;
                // Db::startTrans();
                // try {
                //     //是否采用模型验证
                //     if ($this->modelValidate) {
                //         $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                //         $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                //         $this->model->validateFailException(true)->validate($validate);
                //     }
                //     $result = $this->model->allowField(true)->save($params);
                //     Db::commit();
                // } catch (ValidateException $e) {
                //     Db::rollback();
                //     $this->error($e->getMessage());
                // } catch (PDOException $e) {
                //     Db::rollback();
                //     $this->error($e->getMessage());
                // } catch (Exception $e) {
                //     Db::rollback();
                //     $this->error($e->getMessage());
                // }
                // if ($result !== false) {
                //     $this->success();
                // } else {
                //     $this->error(__('No rows were inserted'));
                // }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    public function biaoge($params)
    {
        $file = $params['biaoge'];
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $ci = 0;
        $T = new \app\api\controller\Tpmecmscom;
        $fontcate_id = $T->GetFontcateIdByBId($params['b_id']);

        // try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }


            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号Aj 
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行 69
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);//Aj 
            $diy_val = $currentSheet->getCellByColumnAndRow(36, 6)->getValue();

            // halt($maxColumnNumber);
            if($maxColumnNumber<36){
                $this->error('请传36列的字库表格');
            }
            $pan_num = 0;
            $H_ci = 0;
            //行
            for ($Row = 1; $Row <= $allRow; $Row++) { 
                //列
                $yu = ($Row-1)%7;
                if($yu == 0){
                    $H_ci = 0;
                    $pan_num++;
                                                                    //列 行
                    $pan_name = $currentSheet->getCellByColumnAndRow(1, $Row)->getValue();
                    $pan_id = $T->GetPId($params['b_id'],$pan_num,$pan_name);
                }

                $H_ci++;
                
                for($L = 1; $L <= 36; $L++){
                // 7行一盘实际前6行

                 
                    if($L>1){

                        $data['p_id'] = $pan_id;
                        $data['b_id'] = $params['b_id'];
                        $data['fontcate_id'] = $fontcate_id;
                        $data['x'] = $L-1;
                        $data['y'] = $H_ci;//$Row-($H_ci-1);
                        $data['font'] = $val = $currentSheet->getCellByColumnAndRow($L,$Row)->getValue();
                        if(strlen($val)>0){
                            $f = Db::name('font')->where($data)->find();
                            if(!$f){//没有这条记录
                                $res = Db::name('font')->insert($data);
                                if($res){
                                    $ci++;
                                }
                            }
                        
                        }
                     
                    
                    }

                }
                
                // 当为7的倍数就不存值
            }
            return $ci;

        // }catch (Exception $exception) {
        //     $this->error($exception->getMessage());
        // }

    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['p','b','fontcate'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','x','y','font','initial','weigh']);
                $row->visible(['p']);
				$row->getRelation('p')->visible(['name']);
				$row->visible(['b']);
				$row->getRelation('b')->visible(['name']);
				$row->visible(['fontcate']);
				$row->getRelation('fontcate')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

}
